package com.lebang.service.buss;

import com.alibaba.fastjson.JSON;
import com.lebang.common.util.RequestUtil;
import com.lebang.component.UMengPushComponent;
import com.lebang.domain.MemberInviteRebateRecord;
import com.lebang.domain.MemberRebateTotalmoney;
import com.lebang.domain.MemberWallet;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberNotice;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.member.LbbMemberTrade;
import com.lebang.example.LbbMemberTradeExample;
import com.lebang.mapper.*;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.NoticeType;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TradeCategory;
import com.lebang.model.enums.buss.TradeStatus;
import com.lebang.service.MemberInviteRebateRecordService;
import com.lebang.service.MemberNoticeService;
import com.lebang.service.MemberRebateTotalmoneyService;
import com.lebang.service.PointService;
import com.lebang.service.sys.DictService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 钱包
 *
 * @author weizx
 * @className WalletService
 * @date 2018年7月25日 下午6:41:57
 */
@Service
public class WalletService {

    @Autowired
    private MemberTradeService memberTradeService;

    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private LbbMemberNoticeMapper lbbMemberNoticeMapper;
    @Autowired
    private LbbMemberTradeMapper lbbMemberTradeMapper;
    @Autowired
    private MemberInviteStatisticsService memberInviteStatisticsService;
    @Autowired
    private UMengPushComponent uMengPushComponent;
    @Autowired
    private PointService pointService;
    @Autowired
    private MemberInviteDetailService memberInviteDetailService;
    @Autowired
    private MemberRebateTotalmoneyService memberRebateTotalmoneyService;
    @Autowired
    private MemberInviteRebateRecordService memberInviteRebateRecordService;
    @Autowired
    private MemberInviteRebateRecordMapper memberInviteRebateRecordMapper;
    @Autowired
    private MemberWalletMapper memberWalletMapper;
    public Integer cash(@Param("userid") String userid, @Param("appid") String appid, @Param("category") String category,
                        @Param("type") String type, @Param("sdate") String sdate, @Param("edate") String edate){
        return lbbMemberTradeMapper.sum(userid, appid, TradeCategory.Income.name(), type, null, null);
    }



    /**
     * 累计总提现成功
     *
     * @param userid
     * @param appid
     * @return
     */
    public Integer cashMoney(String userid, String appid) {
//        String type = RewardType.Cash.name();
//        Integer lift;
//        String liftKey = memberTradeService.getCashMoneyInRedis(userid);
//        if (liftKey == null) {
//            lift = lbbMemberTradeMapper.sum(userid, appid, TradeCategory.Outlay.name(), type, null, null);
//            memberTradeService.initAllCashToRedis(userid, lift);
//        } else {
//            lift = Integer.valueOf(liftKey);
//        }
//        return lift;
        Optional<MemberWallet> optionalMemberWallet=Optional.ofNullable(memberWalletMapper.selectByPrimaryKey(userid));
        return optionalMemberWallet.map(memberWallet -> memberWallet.getAllCash().intValue()).orElse(0);
    }

    /**
     * 累计总收入
     *
     * @param userid
     * @param appid
     * @return
     */
    public Integer totalMoney(String userid, String appid) {
//        int i = dictService.selectIntByKeyName("open_waller_cache");
//        if (i > 0) {
//            String type = RewardType.Cash.name();
//            Integer all;
//            String allKey = memberTradeService.getAllMoneyInRedis(userid);
//            if (allKey == null) {
//                all = lbbMemberTradeMapper.sum(userid, appid, TradeCategory.Income.name(), type, null, null);
//                memberTradeService.initAllMoneyToRedis(userid, all);
//            } else {
//                all = Integer.valueOf(allKey);
//            }
//            return all;
//        } else {
//
//            String type = RewardType.Cash.name();
//            return lbbMemberTradeMapper.sum(userid, appid, TradeCategory.Income.name(), type, null, null);
//        }
        Optional<MemberWallet> optionalMemberWallet=Optional.ofNullable(memberWalletMapper.selectByPrimaryKey(userid));
        return optionalMemberWallet.map(memberWallet -> memberWallet.getAllMoney().intValue()).orElse(0);
    }



    /**
     * 判断是否可提现
     *
     * @param userid
     * @param appid
     * @return
     * @author weizx
     * @date 2018年7月25日 下午8:36:53
     */
    public boolean allow(String userid, String appid) {

        LbbMemberTradeExample example = new LbbMemberTradeExample();
        example.createCriteria()
                .andHasDeletedEqualTo(Booleans.False.name())
                .andMemberIdEqualTo(userid)
                .andAppIdEqualTo(appid)
                .andCategoryEqualTo(TradeCategory.Outlay.name())
                .andTypeEqualTo(RewardType.Cash.name())
                .andStatusEqualTo(TradeStatus.Empty.name());
        List<LbbMemberTrade> trade = lbbMemberTradeMapper.selectByExample(example);
        if (trade.size() == 0) {
            return true;
        }
        return false;

    }

    /**
     * 可提现金额
     *
     * @param userid
     * @param appid
     * @return
     * @author weizx
     * @date 2018年7月25日 下午9:01:49
     */
    public Integer getAllows(String userid, String appid) {
        Integer lift = lbbMemberTradeMapper.sum(userid, appid, TradeCategory.Outlay.name(), RewardType.Cash.name(), null,
                null);
        Integer total = lbbMemberTradeMapper.totalSuccess(userid, appid, TradeCategory.Income.name(),
                RewardType.Cash.name());
        return (total - lift);
    }

    /**
     * 奖励
     *
     * @param record
     * @param catetory
     * @param taskid
     * @param title
     * @param amount
     * @author weizx
     * @date 2018年7月26日 下午7:17:45
     */
    //
    public void income(String memberId, LbbMemberRecord record, TaskCategory catetory, String taskid, String title,
                       Integer amount) {
        String appDesc;

        if (record.getRewordType().equals(0)) {
            // 写入收支明细加钱的
            memberTradeService.addMoney(memberId, amount, title, title, record.getOrderId(),
                    RequestUtil.getHeader(record), JSON.toJSONString(record),
                    new MoneyCategory(Whether.YES, TaskCategory.Common,
                            new BigDecimal(record.getIncrease()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
            // 写入通知
            appDesc = "任务通知:任务:{title}已完成，获得{amount}元!";
            appDesc = appDesc.replace("{title}", title).replace("{amount}",
                    new BigDecimal(amount).divide(new BigDecimal(100)).setScale(2).toString());
        } else {
            // 写入收支明细加金币的
            pointService.addPoint(memberId, amount, TaskCategory.Common, RequestUtil.getHeader(record),"");
            // 写入通知
            appDesc = "任务通知:任务:{title}已完成，获得{amount}金币!";
            appDesc = appDesc.replace("{title}", title).replace("{amount}", amount.toString());
        }


        this.notice(record, record.getCategory().getTitle(), appDesc);
    }


    /**
     * 新用户在14 天内 第一次完成任务的邀新奖励
     *
     * @param memberId
     * @param money
     * @param record
     */
    //
    public void income(String memberId, int money, LbbMemberRecord record) {
        memberTradeService.addMoney(memberId, money, "邀新红包奖励",
                "新用户的邀新红包奖励", record.getOrderId(),
                RequestUtil.getHeader(record), JSON.toJSONString(record), new MoneyCategory(Whether.YES, TaskCategory.MASTER));
        String appDesc = "恭喜！任务：“{title}”已完成，获得{amount}元奖励！";
        appDesc = appDesc.replace("{title}", "邀新红包奖励").replace("{amount}",
                new BigDecimal(money).divide(new BigDecimal(100)).setScale(2).toString());
        notice(record, record.getCategory().getTitle(), appDesc);
    }


    /**
     * 写入，发送通知
     *
     * @param record
     * @param desc
     * @author weizx
     * @date 2018年7月27日 下午2:41:35
     */
    @SuppressWarnings("static-access")
    public void notice(LbbMemberRecord record, String title, String desc) {
        String appDesc = "任务通知";
        LbbMember member = lbbMemberMapper.getMemberByMemberId(record.getMemberId());
        if (member == null) {
            return;
        }
        try {
            uMengPushComponent.sendAndroidCustomizedcast(appDesc, desc, record.getMemberId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        member.setNoticeCount(member.getNoticeCount() + 1);
        lbbMemberMapper.updateByPrimaryKeySelective(member);
        LbbMemberNotice notice = new LbbMemberNotice();
        notice.setAppId(record.getAppId());
        notice.setAppStore(record.getAppStore());
        notice.setCategory(NoticeType.Text);
        notice.setContent("");
        notice.setMemberId(record.getMemberId());
        notice.setStatus("On");
        notice.setSubtitle(desc);
        notice.setTitle(title);
        notice.setHasDeleted(Booleans.False.name());
        notice.setCreateTime(new Date());
        lbbMemberNoticeMapper.insertSelective(notice);

    }







    @SuppressWarnings("static-access")
    public void notice2(LbbMemberTrade trade, String title, String desc) {

        LbbMember member = lbbMemberMapper.getMemberByMemberId(trade.getMemberId());
        try {
            uMengPushComponent.sendAndroidCustomizedcast(title, desc, member.getMemberId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        member.setNoticeCount(member.getNoticeCount() + 1);
        lbbMemberMapper.updateByPrimaryKeySelective(member);
        LbbMemberNotice notice = new LbbMemberNotice();
        notice.setAppId(trade.getAppId());
        notice.setAppStore(trade.getAppStore());
        notice.setCategory(NoticeType.Text);
        notice.setContent("");
        notice.setMemberId(trade.getMemberId());
        notice.setStatus("On");
        notice.setSubtitle(desc);
        notice.setTitle(title);
        lbbMemberNoticeMapper.insertSelective(notice);
    }





    public int checkincome(String memberId) {
        //通过memberid获取徒弟id集合
        List<String> list = memberInviteDetailService.getTdByMemberId(memberId);

        return memberTradeService.checkincome(list);

    }




    public Integer selecMoneyById(String memberId, LocalDateTime min, LocalDateTime max) {
        String type = RewardType.Cash.name();
        return lbbMemberTradeMapper.summoney(memberId, TradeCategory.Income.name(), type, min, max);
    }

    @Autowired
    private DictService dictService;
    @Autowired
    private MemberNoticeService noticeService;


    /**
     * 徒弟完成任务给师傅返利
     *
     * @param member 徒弟
     * @param master 师傅
     * @param money  计算返利的总金额
     * @param type   0 徒弟  1 徒孙
     */
    public void rebateToMaster(LbbMember member, LbbMember master, BigDecimal money, int type, RequestHeaders header,String title,String remark) {
        //低于一分不返利
        if (money.compareTo(new BigDecimal("0.01")) >= 0) {
            int masterMoney = money.multiply(new BigDecimal(100)).intValue();
            MemberRebateTotalmoney memberRebateTotalmoney = memberRebateTotalmoneyService.selectById(member.getMemberId());
            int de = 0;
            int mo = 0;
            //根据类型获取徒弟或者徒孙的最大返利额度
            if (type == 0) {
                mo = dictService.selectIntByKeyName("td_max") * 100;
            } else {
                mo = dictService.selectIntByKeyName("ts_max") * 100;
            }
            if ((type == 0 ? memberRebateTotalmoney.getTotalMoney() : memberRebateTotalmoney.getTotalTsMoney()) <= mo) {
                if ((type == 0 ? memberRebateTotalmoney.getTotalMoney() : memberRebateTotalmoney.getTotalTsMoney()) + masterMoney >= mo) {
                    //计算当类型为0或1时相对应返利值
                    de = mo - (type == 0 ? memberRebateTotalmoney.getTotalMoney() : memberRebateTotalmoney.getTotalTsMoney());
                    if (de > 0) {
                        de = mo - (type == 0 ? memberRebateTotalmoney.getTotalMoney() : memberRebateTotalmoney.getTotalTsMoney());
                    } else {
                        return;
                    }
                } else {
                    de = masterMoney;
                }
            }
            BigDecimal bi = new BigDecimal(de).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
            // memberTradeService.addMoneyByMater(master.getMemberId(), de, type == 0 ? "徒弟赚钱返利" : "徒孙赚钱返利", type, member.getMemberId(),header);
            memberTradeService.addMoney(master.getMemberId(), de,
                    type == 0 ? "徒弟赚钱返利"+title : "徒孙赚钱返利"+title,
                    type == 0 ? "徒弟赚钱返利"+remark : "徒孙赚钱返利"+remark,
                    "", header, "", new MoneyCategory(Whether.YES, TaskCategory.MASTER).notMaster());
            noticeService.addNoticeAndPush((type == 0 ? "您的徒弟尾号" : "您的徒孙尾号") + (member.getPhone().substring(7, 11)) + "完成任务", "兼职咸鱼到账" + bi + "元", master.getMemberId(), header);
            //.一个徒弟/徒孙可给师傅带来的最高收益累计/此时id为等级最低的徒孙id
            memberRebateTotalmoneyService.addTotalMoney(member.getMemberId(), type, de);
            //计入累计收益
            memberInviteStatisticsService.addTotalAmount(master.getMemberId(), de, type);
            //师徒收益存入redis
            memberInviteRebateRecordService.settoday(master.getMemberId(), de);

            MemberInviteRebateRecord rebateRecord = new MemberInviteRebateRecord();
            rebateRecord.setCreateTime(LocalDateTime.now());
            rebateRecord.setMemberId(member.getMemberId());
            rebateRecord.setMoney(de);
            rebateRecord.setType(type);
            rebateRecord.setInviteId(master.getMemberId());
            rebateRecord.setRateRebate(0);
            memberInviteRebateRecordMapper.insert(rebateRecord);
        }
    }



}
